class Admin::NewsController < Admin::AdminController
  before_action :find_news, only: [:show, :edit, :update, :destroy]

  def index
    @news = News.all
    @news = @news.where(newsable_type: params[:type], newsable_id: params[:id]) if params[:type] && params[:id]
    @news = @news.page params[:page]
  end

  def new
    @news = News.new
  end

  def create
    @news = News.new(news_params)
    if @news && @news.save
      redirect_to "#{admin_news_index_path}?type=#{@news.newsable_type}&id=#{@news.newsable_id}"
    else
      render :new
    end
  end

  def show
  end

  def edit
  end

  def update
    if @news && @news.update(news_params)
      redirect_to admin_news_path
    else
      render :edit
    end
  end

  def destroy
    if @news
      @news.destroy
    end
    redirect_to admin_news_index_path
  end

  private
  def news_params
    params.require(:news).permit(:title, :url, :cover, :newsable_type, :newsable_id)
  end

  def find_news
    @news = News.find(params[:id])
  end
end
